import React, { useState, useEffect } from 'react';
import ProLayout from '@ant-design/pro-layout';
import { Input, Avatar, Image } from 'antd';
import { connect } from 'umi';
import { userMenuOperation } from '@/utils/option/layouts';
import { menuTransform } from '@/utils/layouts';
import defaultMenuData from '@/assets/script/menu';
import MenuOperationDOM from '@/components/menuOption';
import LayoutHanderDOM from './layoutHander';
import LayoutMask from './mask';

import './index.less';
const LayouHome = (props) => {
  const { dispatch, selectedKeys, openKeys, settings } = props;

  // 显示前对菜单数据进行查看 - 搜索时的标志位
  const [keyWord, setKeyWord] = useState('');
  // 当前应用会话的位置信息
  const [pathname, setPathname] = useState('/layout');
  // 菜单显示集合
  const [menuData, setMenuData] = useState([]);

  // 初始化
  useEffect(async () => {
    // 初始化展示菜单的集合
    // const listdata = returnMenuData(defaultMenuData);
    setMenuData(defaultMenuData);
    // 初始化菜单集合中的 map => path
    const pathMap = defaultMenuData.map((m) => m.path);
    await dispatch({ type: 'layoutApi/setAllMenuMap', payload: pathMap });
    // 设置默认固定标签栏
    const newMenuChildData = menuTransform(defaultMenuData);
    await dispatch({ type: 'layoutApi/setMenuClassTransform', payload: newMenuChildData });
    const item = newMenuChildData.find((f) => f.path == settings.defaultMenuTab);
    const newTabs = [{ ...item, closable: false }];
    // 初始化头部标签栏
    await dispatch({ type: 'layoutApi/setPushHeaderTabs', payload: newTabs });
    // 初始化头部标签栏当前激活key
    await dispatch({ type: 'layoutApi/setTabsActiveKey', payload: settings.defaultMenuTab });
  }, []);

  // 整理菜单
  const returnMenuData = (data = []) => {
    return data.filter((item) => {
      if (item.children?.length > 0) {
        item.children = returnMenuData(item.children);
      }
      if (item.isHidden) {
        return false;
      } else {
        return true;
      }
    });
  };

  // 自定义的菜单头区域 - 头像个人信息
  const renderUserImage = () => {
    return (
      <MenuOperationDOM
        data={userMenuOperation}
        content={
          <Avatar
            size={64}
            icon={<Image preview={false} src={`${DEV_URL}:7777/image/juejin/user_img.png`} />}
          />
        }
        onMenuChange={onPushTabMenu}
        propsOption={{ placement: 'topRight' }}
      />
    );
  };

  // 添加到tab中
  const onPushTabMenu = async (target) => {
    // 如果标签栏中不存在则 更新
    await dispatch({ type: 'layoutApi/isSetTabsData', record: target });
    // 更新头部标签栏当前激活key
    await dispatch({ type: 'layoutApi/setTabsActiveKey', payload: target.key });
  };

  // 在菜单标题的下面渲染一个区域 - 搜索菜单
  const renderSearchMenuBottom = ({ collapsed }) => {
    return !collapsed && <Input.Search onSearch={(e) => setKeyWord(e)} />;
  };

  // 显示前对菜单数据进行查看 - 菜单
  const filterByMenuDate = (data, keyWord) => {
    return data
      .map((item) => {
        if (
          (!item.isHidden && item.name && item.name.includes(keyWord)) ||
          filterByMenuDate(item.children || [], keyWord).length > 0
        ) {
          return {
            ...item,
            children: filterByMenuDate(item.children || [], keyWord),
          };
        }
        return undefined;
      })
      .filter((item) => item);
  };

  // 自定义菜单项的 render 方法
  const renderMenuItem = (item, dom) => {
    return <a onClick={() => menuEventPage(item)}>{dom}</a>;
  };

  // 点击菜单查看页面
  const menuEventPage = async (record) => {
    setPathname(record.path);
    await dispatch({ type: 'layoutApi/setIframeUrl', target: record.key });
    // 如果标签栏中不存在则 更新
    await dispatch({ type: 'layoutApi/isSetTabsData', record });
    // 更新头部标签栏当前激活key
    await dispatch({ type: 'layoutApi/setTabsActiveKey', payload: record.key });
  };

  // 操作菜单的函数
  const onOpenChange = async (openKeys) => {
    await dispatch({ type: 'layoutApi/setOpenKeys', payload: openKeys });
  };

  // 选中菜单时调用
  const onSelect = async ({ selectedKeys }) => {
    await dispatch({ type: 'layoutApi/setMenuSelectKeys', payload: selectedKeys });
  };

  return (
    <>
      <ProLayout
        className="layout-content"
        title="后台管理系统"
        route={{ routes: menuData }} // 用于生成菜单和面包屑
        location={{ pathname }} // 当前应用会话的位置信息
        menuExtraRender={renderSearchMenuBottom} // 搜索菜单
        menuHeaderRender={renderUserImage} // 顶部头像
        menuItemRender={renderMenuItem} // 渲染菜单的item
        postMenuData={(menus) => filterByMenuDate(menus || [], keyWord)} // 在显示前对菜单数据进行查看
        menuProps={{ selectedKeys, onSelect, openKeys, onOpenChange }} // antd 中 menu 的属性
      >
        <LayoutHanderDOM />
      </ProLayout>

      <LayoutMask {...props} />
    </>
  );
};

export default connect(({ layoutApi, settings }) => ({
  settings,
  openKeys: layoutApi.openKeys,
  selectedKeys: layoutApi.selectedKeys,
}))(LayouHome);
